package cn.org.xuanzp.accept.provider.impl;

import cn.org.xuanzp.accept.handler.AcceptCommandHandler;
import cn.org.xuanzp.accept.provider.AcceptProvider;
import cn.org.xuanzp.common.command.impl.MessageCommand;
import cn.org.xuanzp.common.utils.CommandUtils;
import cn.org.xuanzp.nty.utils.NettyServerUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Classname MessageProvider
 * @Description 消息
 * @Version 1.0.0
 * @Date 2024/9/22 0:38
 * @Created by xuanzp
 */
public class MessageProvider implements AcceptProvider<MessageCommand> {

    private AcceptCommandHandler acceptCommandHandler;

    public MessageProvider(AcceptCommandHandler acceptCommandHandler) {
        this.acceptCommandHandler = acceptCommandHandler;
    }

    public void setAcceptCommandHandler(AcceptCommandHandler acceptCommandHandler) {
        this.acceptCommandHandler = acceptCommandHandler;
    }

    /***
     * 接受消息
     * @param messageCommand
     */
    @Override
    public void accept(MessageCommand messageCommand) {
        if(support(messageCommand)){
            Map<String, Object> headers = messageCommand.getHeaders();
            // 获取消息目标ID
            String toId = (String) headers.get(CommandUtils.COMMAND_HEADER_TO);
            if(NettyServerUtil.existCtx(toId)){
                // 转发
                acceptCommandHandler.transmit(messageCommand);
            }else{
                List<String> nodes = (List<String>) headers.get(CommandUtils.COMMAND_HEADER_NODES);
                if(nodes == null){
                    nodes = new ArrayList<String>();
                }
                String node = "";
                nodes.add(node);

                headers.put(CommandUtils.COMMAND_HEADER_NODES,nodes);
                // 向上级节点推送
                routeCommand(messageCommand);
            }
        }
    }

    /***
     * 向上级节点推送
     * @param messageCommand
     */
    private void routeCommand(MessageCommand messageCommand) {
        acceptCommandHandler.route(messageCommand);
    }

    /*private Object getClient(String toId) {
        // tod 获取客户端
        return null;
    }*/

    /***
     * 判断是否支持
     * @param o
     * @return
     */
    @Override
    public Boolean support(Object o) {
        return o instanceof MessageCommand;
    }
}
